#include <climits>
class Solution {
public:
    int FindMin(vector<ListNode*>& lists)
    {
        int _min = INT_MAX;
        int index = -1;
        for (int i = 0; i < lists.size(); i++)
        {
            if (lists[i] && lists[i]->val < _min)
            {
                index = i;
                _min = lists[i]->val;
            }
        }
        return index;
    }
    bool Check(vector<ListNode*>& lists)
    {
        for (auto& e : lists)
        {
            if (e != nullptr)
                return true;
        }
        return false;
    }
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        vector<ListNode*> v;
        while (Check(lists))
        {
            int i = FindMin(lists);
            ListNode* tmp = lists[i];
            lists[i] = lists[i]->next;
            tmp->next = nullptr;

            v.push_back(tmp);
        }
        for (int i = 1; i < v.size(); ++i)
        {
            v[i - 1]->next = v[i];
        }
        if (v.size() != 0)
            v.back()->next = nullptr;
        return v.size() == 0 ? nullptr : v[0];
    }
};